package main

import "fmt"

/**
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

给定一个只包含(){}[]字符的字符串，判定该字符串是否按正确顺序闭合

分析: 这种问题通常使用栈解决比较方便
http://bangbingsyb.blogspot.com/2014/11/leetcode-valid-parentheses.html


*/

func isValid(s string) bool {
	stack := []byte{}

	for i := 0; i < len(s); i++ {
		if s[i] == '(' || s[i] == '{' || s[i] == '[' {
			stack = append(stack, s[i])
		} else if s[i] == ')' {
			if len(stack) == 0 || stack[len(stack)-1] != '(' {
				return false
			} else {
				stack = stack[:len(stack)-1]
			}
		} else if s[i] == ']' {
			if len(stack) == 0 || stack[len(stack)-1] != '[' {
				return false
			} else {
				stack = stack[:len(stack)-1]
			}
		} else if s[i] == '}' {
			if len(stack) == 0 || stack[len(stack)-1] != '{' {
				return false
			} else {
				stack = stack[:len(stack)-1]
			}
		}
	}

	if len(stack) == 0 {
		return true
	} else {
		return false
	}
}

type stack struct {
	l    int
	data []rune
}

func (s *stack) pop() rune {
	if s.isEmpty() {
		return ' '
	} else {
		r := s.data[s.Len()-1]
		s.data = s.data[:s.Len()-1]
		s.l--
		return r
	}
}

func (s *stack) push(i rune) {
	s.data = append(s.data, i)
	s.l++
}

func (s *stack) peak() rune {
	if s.Len() > 0 {
		return s.data[s.Len()-1]
	} else {
		return ' '
	}
}

func (s *stack) isEmpty() bool {
	if s.Len() == 0 {
		return true
	} else {
		return false
	}
}

func (s *stack) Len() int {
	return s.l
}

func newStack() *stack {
	return &stack{l: 0, data: []rune{}}
}

func main() {
	//s := newStack()
	//s.push('b')
	//s.push('a')
	//s.push('t')
	//fmt.Printf("%c", s.pop())
	//fmt.Printf("%c", s.pop())
	str := "()[]{}"
	if isValid(str) {
		fmt.Print("success")
	} else {
		fmt.Print("fail")
	}
}
